﻿using System;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using ChannelVN.Cached.Common;
using ChannelVN.Cached.Config;
using ChannelVN.Cached;
using ChannelVN.Cached.Entity;
using ChannelVN.Cached.UrlRewrite;

namespace ChannelVN.Cached.UrlRewrite
{
    public class UrlRewriteModule : IHttpHandlerFactory, IRequiresSessionState
    {
        static readonly string[] mobiles = new string[] {
                                                    "iphone","opera mini", "sony", "htc", "moto", "panasonic", "sharp", "philips", "samsung"
                                                    , "android", "nokia", "blackberry", "galaxy"
                                             };
        public static bool IsExistCookieNoRedirect()
        {
            bool isReturn = false;
            string AbsolutePath = HttpContext.Current.Request.Url.Query;
            if (AbsolutePath.IndexOf("mobile=true") >= 0)
            {
                isReturn = true;
                HttpCookie cookie = new HttpCookie("browser.channelvn_sohanews", "web.channelvn_sohanews");
                try
                {
                    cookie.Expires = DateTime.Now.AddMinutes(30);
                    HttpContext.Current.Response.Cookies.Add(cookie);
                }
                catch (Exception ex)
                {

                }

            }
            else if (AbsolutePath.IndexOf("removecookie=true") >= 0)
            {
                isReturn = false;
                HttpCookie myCookie = HttpContext.Current.Request.Cookies.Get("browser.channelvn_sohanews");
                if (myCookie != null)
                    myCookie.Values.Clear();
            }
            else
            {

                HttpCookie myCookie = HttpContext.Current.Request.Cookies.Get("browser.channelvn_sohanews");
                if (myCookie != null && myCookie.Value.ToLower() == "web.channelvn_sohanews")
                {
                    isReturn = true;
                }


            }

            return isReturn;
        }
        public static bool IsMobileRedirect(HttpContext context)
        {
            bool isReturn = false;
            if (context.Request.Browser["IsMobileDevice"] == "true")
            {
                isReturn = true;
            }
            return isReturn;
        }

        public static bool isMobileBrowser(HttpContext context)
        {
            //GETS THE CURRENT USER CONTEXT
            // HttpContext context = HttpContext.Current;

            //FIRST TRY BUILT IN ASP.NT CHECK
            if (context.Request.Browser.IsMobileDevice)
            {
                return true;
            }
            //THEN TRY CHECKING FOR THE HTTP_X_WAP_PROFILE HEADER
            if (context.Request.ServerVariables["HTTP_X_WAP_PROFILE"] != null)
            {
                return true;
            }
            //THEN TRY CHECKING THAT HTTP_ACCEPT EXISTS AND CONTAINS WAP
            if (context.Request.ServerVariables["HTTP_ACCEPT"] != null &&
                context.Request.ServerVariables["HTTP_ACCEPT"].ToLower().Contains("wap"))
            {
                return true;
            }
            //AND FINALLY CHECK THE HTTP_USER_AGENT 
            //HEADER VARIABLE FOR ANY ONE OF THE FOLLOWING
            if (context.Request.ServerVariables["HTTP_USER_AGENT"] != null)
            {



                //Loop through each item in the list created above 
                //and check if the header contains that text
                foreach (string s in mobiles)
                {
                    if (context.Request.ServerVariables["HTTP_USER_AGENT"].
                                                        ToLower().Contains(s.ToLower()))
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        public static bool RedirectToMobile(string url)
        {
            if (!string.IsNullOrEmpty(url))
            {
                string host = "http://m.soha.vn";
                if (host.EndsWith("/")) host = host.Substring(0, host.Length - 1);

                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Status = "301 Moved Permanently";
                HttpContext.Current.Response.AddHeader("Location", host + (url.StartsWith("/") ? "" : "/") + url);
                HttpContext.Current.Response.End();

                return true;
            }

            return false;
        }

        public IHttpHandler GetHandler(HttpContext context, string requestType, string url1, string pathTranslated)
        {
            string rewrite = "";
            string url = context.Request.Url.AbsolutePath;
            //string url = context.Request.RawUrl;

            #region Mobile redirection

            if (IsMobileRedirect(context) || isMobileBrowser(context))
            {
                if (!IsExistCookieNoRedirect())
                {
                    if (url.IndexOf(".htm") != -1)
                    {
                        context.Response.Redirect("http://m.soha.vn" + url);
                    }
                    else
                        context.Response.Redirect("http://m.soha.vn");
                }
            }

            #endregion

            #region Custom rewrite

            var rawurl = url.ToLower();
            if (
                rawurl.Contains("/bao/") ||
                rawurl.Contains("/fun/")
                )
            {

                _301Redirection.RedirectTo("/");
            }

            #endregion

            #region Virtual url

            if (HttpContext.Current.Request.Url.Query != String.Empty)
            {
                if (context.Request.Url.Query.Length > 0)
                {
                    context.Items["VirtualUrl"] = context.Request.Path + context.Request.Url.Query;
                }
            }
            if (context.Items["VirtualUrl"] == null)
            {
                context.Items["VirtualUrl"] = context.Request.Path;
            }

            #endregion

            #region 301 redirection

            var _301 = new _301Redirection();
            if (url.EndsWith(".html") || !_301.Redirect(url + (context.Request.Url.Query.Length > 0 ? "?" + HttpContext.Current.Request.Url.Query.Replace("?", "") : "")))
            {
                UrlRewriteRules rewriteRules = UrlRewriteRules.GetCurrentRewriteRules();
                rewrite = rewriteRules.GetMatchingRewrite(url);

                if (!string.IsNullOrEmpty(rewrite))
                {
                    context.RewritePath("~" + rewrite);
                }
                else
                {
                    rewrite = context.Request.Path + context.Request.Url.Query;
                }
            }

            #endregion

            #region parse page

            string newFilePath = rewrite.IndexOf("?") > 0 ? rewrite.Substring(0, rewrite.IndexOf("?")) : rewrite;

            CacheSettings cacheSettings = CacheSettings.GetCurrentSettings();
            if (null != cacheSettings && cacheSettings.EnableCache && cacheSettings.EnableHtmlCached && !CacheController.IsCachedUpdating && !CacheController.IsCachedDeleting)
            {
                PageSettingItem pageCacheSetting = cacheSettings.PageSettings.GetPageSettingByPageFile(newFilePath);

                if (null != pageCacheSetting && pageCacheSetting.EnableCache)
                {
                    string group = CacheController.GetCacheGroup(pageCacheSetting.GroupKey);

                    string cacheKey = CacheController.GetCacheKeyName(pageCacheSetting.CacheNameFormat, cacheSettings.PageSettings.CacheClientName);

                    string cacheContent = CacheController.GetMemcachedInstance(cacheSettings.PageSettings.CacheClientName).Get(group, cacheKey) as string;

                    if (!string.IsNullOrEmpty(cacheContent))
                    {
                        context.Response.ContentType = "text/html";
                        Compres.doCompression();
                        context.Response.Write(cacheContent + "<!-- " + group + "-" + cacheKey + " -->");
                        return context.Handler;
                    }
                }
            }

            if (string.IsNullOrEmpty(newFilePath))
                newFilePath = "/blank.aspx";
            try
            {
                return PageParser.GetCompiledPageInstance(newFilePath, context.Server.MapPath(newFilePath), context);
            }
            catch (Exception ex)
            {
                Lib.WriteLogToFile(ex);
                return PageParser.GetCompiledPageInstance("/404.aspx", context.Server.MapPath("/404.aspx"), context);
            }

            #endregion
        }


        public void ReleaseHandler(IHttpHandler handler)
        {
        }
    }
}
